<template>
  <base-modal 
    :show.sync="visible"
    :title="$t('frameHeader.userFeedback.feedback')"
    class="user-feedback-dialog"
    width="480px"
    @closed="reset"
    v-loading="loading || typesLoading"
  >
    <div class="user-feedback-main">
      <el-form
        :model="form"
        :rules="rules"
        label-position="top"
        ref="form"
      >
        <el-form-item :label="$t('frameHeader.userFeedback.selectFeedbackType')" class="type-item">
          <el-checkbox 
            v-for="(item, index) in type"
            :key="`${index}_type`"
            :label="item.name"
            v-model="item.checked"
          >
            {{item.name}} <span :class="['type-checkbox-span',item.checked?'type-checkbox-checked':'']">{{item.desc}}</span>
          </el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('frameHeader.userFeedback.selectFunctionModule')">
          <el-select
            multiple
            v-model="form.module"
            :placeholder="$t('common.base.pleaseSelect')"
          >
            <el-option
              v-for="item in filteredShowFuncModule"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('frameHeader.userFeedback.feedbackContent')" prop="feedbackContent.content">
          <el-input
            type="textarea"
            maxlength="500"
            :placeholder="$t('frameHeader.userFeedback.problemSuggest')"
            rows="3"
            v-model="form.feedbackContent.content"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('frameHeader.userFeedback.photoSupplement')">
          <el-upload
            action="string"
            list-type="picture-card"
            class="user-feedback-image"
            accept=".jpg,.jpeg,.png,.tiff,.gif,.bmp"
            multiple
            :limit="9"
            :http-request="uploadImage"
            :on-remove="onRemovePic"
            :on-exceed="onExceedPic"
            :file-list="form.feedbackContent.pictures"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div class="avatar-uploader-text">{{$t('frameHeader.userFeedback.uploadImg')}}</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('common.label.contactMethod')" prop="phone">
          <el-input
            v-model="form.phone"
            :placeholder="$t('frameHeader.userFeedback.requiredTel')"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="searchFeedbackRecord">{{$t('frameHeader.userFeedback.recordFeedback')}}</el-button>
      <el-button type="primary" @click="validate">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import Uploader from 'packages/BaseUpload/uploader';
import http from '@src/util/http';
import i18n from '@src/locales'
import { validatePhone } from '@src/util/validator'

/* mixin */
import {
  VersionControlEventMixin,
  VersionControlTaskMixin,
  VersionControlPayMixin,
  VersionControlSparePartMixin,
  VersionControlReportMixin,
  VersionControlServiceMixin,
  VersionControlIMMixin,
  VersionControlWarehouseMixin,
  VersionControlLinkCMixin,
  VersionControlServiceProviderMixin
} from '@src/mixins/versionControlMixin';

export default {
  name: 'create-feed-back',
  mixins: [
    VersionControlEventMixin,
    VersionControlTaskMixin,
    VersionControlPayMixin,
    VersionControlSparePartMixin,
    VersionControlReportMixin,
    VersionControlServiceMixin,
    VersionControlIMMixin,
    VersionControlWarehouseMixin,
    VersionControlLinkCMixin,
    VersionControlServiceProviderMixin
  ],
  props: {
    version: String,
    initData: {
      type: Object,
      default: {},
    },
  },
  data () {
    // 验证固话手机号的规则
    const checkMobile = (rule, value, cb) => {
      if (!value) {
        cb(new Error(i18n.t('common.placeholder.inputPhone2')));
      }
      if (validatePhone(value, 3)) {
        return cb();
      }
      cb(new Error(i18n.t('common.validate.checkTelNumber')));
    };
    return {
      visible: false,
      form: this.buildForm(),
      type:this.buildType(),
      rules: {
        phone: [
          {
            required: true,
            validator: checkMobile,
            trigger: ['blur', 'change']
          }
        ],
        feedbackContent:{
          content: [
            {
              required: true,
              message: i18n.t('frameHeader.userFeedback.pleaseFillTheFeedback'),
              trigger: ['blur', 'change']
            }
          ] 
        },
      },
      myNotification:null,
      loading: false,
      typesLoading: false,
    }
  },
  computed: {
    funcModule() {
      return [
        // 服务台
        {
          label: i18n.t('frameHeader.userFeedback.funModule[0]'),
          show: this._isShowEventModule,
        },
        // 工单
        {
          label: i18n.t('frameHeader.userFeedback.funModule[1]'),
          show: this._isShowTaskModule,
        },
        // 财务管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[2]'),
          show: this._isShowPayModule,
        },
        // 客户信息
        {
          label: i18n.t('frameHeader.userFeedback.funModule[3]'),
          show: true,
        },
        // 产品管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[4]'),
          show: true,
        },
        // 备件管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[5]'),
          show: this._isShowSparePartModule,
        },
        // 运营分析
        {
          label: i18n.t('frameHeader.userFeedback.funModule[6]'),
          show: this._isShowReportModule,
        },
        // 服务管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[7]'),
          show: this._isShowServiceModule,
        },
        // 服务云仓
        {
          label: i18n.t('frameHeader.userFeedback.funModule[8]'),
          show: this._isShowWarehouseModule,
        },
        // 信息管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[9]'),
          show: true,
        },
        // 服务商管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[10]'),
          show: this._isShowServiceProviderModule,
        },
        // 自助门户
        {
          label: i18n.t('frameHeader.userFeedback.funModule[11]'),
          show: this._isShowLinkCModule,
        },
        // 账号权限
        {
          label: i18n.t('frameHeader.userFeedback.funModule[12]'),
          show: true,
        },
        // 系统管理
        {
          label: i18n.t('frameHeader.userFeedback.funModule[13]'),
          show: true,
        },
      ]
    },
    filteredShowFuncModule() {
      return this.funcModule.filter(item => Boolean(item?.show))
    }
  },
  methods: {
    openDialog() {
      this.visible = true;
    },
    buildType() {
      const type = [
        {
          name: i18n.t('frameHeader.userFeedback.performanceExperience'),
          checked: false,
          desc: i18n.t('frameHeader.userFeedback.problem')
        },
        {
          name: i18n.t('frameHeader.userFeedback.dysfunction'),
          checked: false,
          desc: i18n.t('frameHeader.userFeedback.notUsed')
        },
        {
          name: i18n.t('frameHeader.userFeedback.productProposal'),
          checked: false,
          desc: i18n.t('frameHeader.userFeedback.valueUserSuggestions')
        },
        {
          name: i18n.t('common.base.other'),
          checked: false,
          desc:''
        }
      ]
      return type
    },
    buildForm() {
      const form = {
        feedbackType: [], // 反馈类型
        module: [], // 功能模块
        feedbackContent:{
          content: '', // 反馈内容
          pictures: [] // 图片
        },
        phone:'', // 联系方式
        version:'', // 版本号
        equipment:1 // PC端
      }   
      return form;
    },
    initForm() {
      this.$nextTick(()=>{
        this.form = this.buildForm();
        this.type = this.buildType();
      })
    },
    reset() {
      this.initForm();
      this.$refs.form.resetFields()
    },
    uploadImage(param) {
      Uploader.upload(param.file, '/files/upload')
        .then((result) => {
          if (result.status != 0) {
            this.$message({
              message: `${result.message}`,
              duration: 1500,
              type: 'error',
            });
            return;
          }

          let file = result.data;
          let item = {
            uid: param.file.uid,
            id: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          };
          this.$set(this.form.feedbackContent, 'pictures', [
            ...this.form.feedbackContent.pictures,
            item,
          ]);
        })
        .catch((err) => {
          console.warn(err);
        })
        .finally(() => { });
    },
    onRemovePic(o, a) {
      this.$set(this.form.feedbackContent, 'pictures', this.form.feedbackContent.pictures.filter(item => item.uid != o.uid));
    },
    onExceedPic() {
      this.$message.error(i18n.t('frameHeader.userFeedback.uploadNine'));
    },
    validate() {
      this.$refs.form.validate((vaild) =>{
        if(vaild) {
          this.submit(); //提交表单
        }
      })
    },
    async submit() {
      this.typesLoading = true;
      //反馈类型需要手动添加到form
      this.type.forEach((item) => {
        if(item.checked){
          this.form.feedbackType.push(item.name)
        }
      })
      let param = JSON.parse(JSON.stringify(this.form))
      let version = JSON.parse(window._init || '{}').releaseVersion
      this.$set(param, 'version', version)
      let result = await http.post('/api/app/outside/feedback/insertFeedback', param)
      let failure = result.success ? false : true;
      this.initForm(); // 初始化表单
      this.visible = false;
      this.typesLoading = false;
      this.myNotification = this.$platform.notification({
        type: !failure ? 'success' : 'error',
        // title: `提交${!failure ? '成功' : '失败'}`,
        title: !failure ? i18n.t('common.base.tip.submitSuccess') : i18n.t('common.base.submitFail'),
        message: (h => (
          <div> 
            <p style="font-size: 12px;color: #8C8C8C;">{i18n.t('frameHeader.userFeedback.thankFeedback')}</p>
            <a onClick = {this.searchFeedbackRecord} style={{ color: this.getThemeColor, textDecoration: 'underline', fontSize: '12px', cursor: 'pointer' }}>{i18n.t('frameHeader.userFeedback.recordFeedback')}</a>
          </div>
          ))(this.$createElement)
        });
    },
    searchFeedbackRecord() {
      this.visible = false;
      this.$emit('searchFeedBack');
      if(this.myNotification != null) {
        this.myNotification.close();
      }
    }
  }
}
</script>

<style lang="scss">
  .user-feedback-main {
    margin: 21px 20px 30px 20px;
    .el-textarea__inner {
      padding-left: 12px !important;
    }
    .el-input__inner {
      padding-left: 12px !important;
    }
}
  .user-feedback-image {
    .el-upload--picture-card {
      width: 88px;
      height: 88px;
      line-height: 88px;
      margin-bottom: 6px;
      &:hover {
        border-color: $color-primary;
      }
      .avatar-uploader-icon {
        height: 24px;
        line-height: 24px;
        text-align: center;
        margin-top: 17px;
        display: block;
      }
      .avatar-uploader-text {
        height: 22px;
        line-height: 22px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        text-align: center;
        margin-top: 13px;
      }
    }
    .el-upload-list__item {
      width: 88px;
      height: 88px;
    }
  }
</style>
<style lang="scss" scoped>
  .type-item {
    ::v-deep .el-form-item__content {
      line-height: 22px;
      label:not(:last-child) {
        margin-bottom: 8px;
      }
      label {
        display: block;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        .type-checkbox-span {
          font-size: 12px;
          color: #8C8C8C;
        }
        .type-checkbox-checked {
          color: $color-primary;
        }
      }
    }
  }
  .el-select {
    width: 100%;
  }
  .dialog-footer{
    height: 52px;
  }
</style>